"""
规范性分析API路由
提供规范性分析相关的API接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field
from datetime import datetime
from sqlalchemy.orm import Session

from core.database import get_db
from core.auth import get_current_active_user
from models.user import User
from services.analysis.compliance_analyzer import ComplianceAnalyzer, ComplianceAnalysisFilters
from services.analysis.base_analyzer import get_analysis_service

# 创建路由器
compliance_analysis_router = APIRouter()

# 请求模型
class ComplianceAnalysisRequest(BaseModel):
    """规范性分析请求模型"""
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")
    compliance_status: Optional[str] = Field(None, description="合规状态: compliant, non_compliant, partial")
    compliance_type: Optional[str] = Field(None, description="规范性类型")
    issue_category: Optional[str] = Field(None, description="问题类别")
    min_confidence: Optional[float] = Field(None, ge=0.0, le=1.0, description="最小置信度")
    limit: Optional[int] = Field(1000, ge=1, le=10000, description="返回记录限制")
    offset: Optional[int] = Field(0, ge=0, description="偏移量")

class ComplianceTrendsRequest(BaseModel):
    """规范性趋势请求模型"""
    compliance_status: Optional[str] = Field(None, description="特定合规状态")
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")

class RegionalComplianceRequest(BaseModel):
    """区域规范性请求模型"""
    region: Optional[str] = Field(None, description="特定区域")
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")


@compliance_analysis_router.post("/analyze")
async def analyze_compliance(
    request: ComplianceAnalysisRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    执行规范性分析

    返回完整的规范性分析结果，包括：
    - 基础统计信息
    - 合规性分布数据
    - 规范性类型分析
    - 问题类别分析
    - 置信度分析
    - 时间序列数据
    - 规范性详情
    """
    try:
        # 创建过滤器
        filters = ComplianceAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date
        filters.compliance_status = request.compliance_status
        filters.compliance_type = request.compliance_type
        filters.issue_category = request.issue_category
        filters.min_confidence = request.min_confidence
        filters.limit = request.limit
        filters.offset = request.offset

        # 执行分析
        analyzer = ComplianceAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        return {
            "code": 200,
            "message": "规范性分析完成",
            "data": result.data,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"规范性分析失败: {str(e)}")


@compliance_analysis_router.get("/distribution")
async def get_compliance_distribution(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    compliance_status: Optional[str] = Query(None, description="特定合规状态"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取合规性分布统计数据"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.compliance_status = compliance_status

        analyzer = ComplianceAnalyzer(db)
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_compliance_distribution(query, filters)

        return {
            "code": 200,
            "message": "获取合规性分布成功",
            "data": distribution,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取合规性分布失败: {str(e)}")


@compliance_analysis_router.get("/type-analysis")
async def get_compliance_type_analysis(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    compliance_type: Optional[str] = Query(None, description="特定规范性类型"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取规范性类型分析"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.compliance_type = compliance_type

        analyzer = ComplianceAnalyzer(db)
        query = analyzer.build_base_query(filters)
        type_analysis = analyzer.get_compliance_type_analysis(query, filters)

        return {
            "code": 200,
            "message": "获取规范性类型分析成功",
            "data": type_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取规范性类型分析失败: {str(e)}")


@compliance_analysis_router.get("/issue-analysis")
async def get_issue_category_analysis(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    issue_category: Optional[str] = Query(None, description="特定问题类别"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取问题类别分析"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.issue_category = issue_category

        analyzer = ComplianceAnalyzer(db)
        query = analyzer.build_base_query(filters)
        issue_analysis = analyzer.get_issue_category_analysis(query, filters)

        return {
            "code": 200,
            "message": "获取问题类别分析成功",
            "data": issue_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取问题类别分析失败: {str(e)}")


@compliance_analysis_router.get("/confidence-analysis")
async def get_compliance_confidence_analysis(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    compliance_status: Optional[str] = Query(None, description="特定合规状态"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取规范性置信度分析"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.compliance_status = compliance_status

        analyzer = ComplianceAnalyzer(db)
        query = analyzer.build_base_query(filters)
        confidence_analysis = analyzer.get_confidence_analysis(query, filters)

        return {
            "code": 200,
            "message": "获取置信度分析成功",
            "data": confidence_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取置信度分析失败: {str(e)}")


@compliance_analysis_router.get("/compliance-details")
async def get_compliance_details(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    compliance_status: Optional[str] = Query(None, description="特定合规状态"),
    limit: Optional[int] = Query(10, ge=1, le=50, description="返回记录数量限制"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取规范性详情"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.compliance_status = compliance_status

        analyzer = ComplianceAnalyzer(db)
        query = analyzer.build_base_query(filters)
        compliance_details = analyzer.get_compliance_details(query, filters, limit)

        return {
            "code": 200,
            "message": "获取规范性详情成功",
            "data": compliance_details,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取规范性详情失败: {str(e)}")


@compliance_analysis_router.post("/trends")
async def get_compliance_trends(
    request: ComplianceTrendsRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取规范性趋势分析"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date
        filters.compliance_status = request.compliance_status

        analyzer = ComplianceAnalyzer(db)
        trends = analyzer.get_compliance_trends(filters)

        return {
            "code": 200,
            "message": "获取规范性趋势成功",
            "data": trends,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取规范性趋势失败: {str(e)}")


@compliance_analysis_router.post("/regional-analysis")
async def get_regional_compliance(
    request: RegionalComplianceRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取区域规范性分析"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date

        analyzer = ComplianceAnalyzer(db)
        regional_compliance = analyzer.get_compliance_by_region(filters)

        return {
            "code": 200,
            "message": "获取区域规范性分析成功",
            "data": regional_compliance,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取区域规范性分析失败: {str(e)}")


@compliance_analysis_router.get("/time-series")
async def get_compliance_time_series(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    compliance_status: Optional[str] = Query(None, description="特定合规状态"),
    granularity: Optional[str] = Query("day", description="时间粒度: day, week, month"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取规范性时间序列数据"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.compliance_status = compliance_status

        analyzer = ComplianceAnalyzer(db)
        time_series = analyzer.get_time_series_data(filters, granularity)

        return {
            "code": 200,
            "message": "获取时间序列成功",
            "data": time_series,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取时间序列失败: {str(e)}")


@compliance_analysis_router.get("/summary")
async def get_compliance_summary(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取规范性分析摘要"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date

        analyzer = ComplianceAnalyzer(db)
        basic_stats = analyzer.get_basic_statistics(filters)

        # 获取简要的合规性分布
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_compliance_distribution(query, filters)

        # 获取置信度分析
        confidence_analysis = analyzer.get_confidence_analysis(query, filters)

        summary = {
            "basic_statistics": basic_stats,
            "compliance_overview": {
                "compliance_rate": distribution.get("compliance_rate", 0),
                "total_compliant": distribution.get("compliant_count", 0),
                "total_non_compliant": distribution.get("non_compliant_count", 0),
                "total_partial": distribution.get("partial_count", 0)
            },
            "status_distribution": distribution.get("status_distribution", {}),
            "average_confidence": confidence_analysis.get("average_confidence", 0)
        }

        return {
            "code": 200,
            "message": "获取规范性摘要成功",
            "data": summary,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取规范性摘要失败: {str(e)}")


@compliance_analysis_router.get("/export")
async def export_compliance_data(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    compliance_status: Optional[str] = Query(None, description="特定合规状态"),
    format: str = Query("json", description="导出格式: json, csv"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """导出规范性分析数据"""
    try:
        filters = ComplianceAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.compliance_status = compliance_status

        analyzer = ComplianceAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        if format == "json":
            return {
                "code": 200,
                "message": "数据导出成功",
                "data": result.data,
                "format": "json",
                "timestamp": datetime.now().isoformat()
            }
        elif format == "csv":
            # 这里可以实现CSV导出逻辑
            raise HTTPException(status_code=400, detail="CSV导出功能待实现")
        else:
            raise HTTPException(status_code=400, detail="不支持的导出格式")

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导出数据失败: {str(e)}")